import * as React from 'react';
import produce from 'immer'
import { IComponent } from '@bastet/widgets';
import { createInformationFunc } from "./func";


export type Information = {
  index: any[],
  data: IComponent
}

interface IReducerStateParams {
  value: any; field: string; index: string
}
function reducerState(state: IComponent, action: IComponent): IComponent {
  console.log('%cnextState:after', 'background: goldenrod;', action)
  return action || state
}

export function useStateReducer() {
  const [state, dispatch] = (React.useReducer as any)(reducerState, [])

  const changeField = ({ value, field, index }: IReducerStateParams) => {
    const __index = index.split('-');
    console.log('nextState:before', { value, field, index }, __index)
    const nextState = produce(state, (draft: IComponent[]) => {
      const func = createInformationFunc(__index as any);

      console.log('createInformationFunc', func, draft)
      func(draft, (data: any) => {
        console.log('createInformationFunc', data)
        if (data) {
          if(field.indexOf('.') > -1) {
            try {
              const execFunc = new Function('data', 'path', 'val', `data.${field} = val`)
              execFunc(data.renderProps, field, value)
            } catch (e) {
              console.error(`“${field}” 在 renderProps 上找不到，无法赋值，请检查代码！\r\n`, e)
            }
          } else {
            data.renderProps[field] = value
          }
        }

        return data
      })
    });

    dispatch(nextState as any)
  }

  return [state, dispatch, changeField]
}

let informationDefault: Information // = originalState.children[0] as Information;
function reducerInfo(state: Information[], action: any) {
  return action || state
}

export function useInformationReducer<T>(defData: IComponent[]): [T, any] {
  const [information, dispatch] = React.useReducer<any>(reducerInfo, informationDefault || defData)

  return [information as T, dispatch]
}